package com.hbnu.system.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hbnu.system.config.BaseException;
import com.hbnu.system.constant.AuthorTypeConstants;
import com.hbnu.system.mapper.Art_authorMapper;
import com.hbnu.system.model.entity.Art;
import com.hbnu.system.model.entity.Art_author;
import com.hbnu.system.model.entity.Porprojectauthor;
import com.hbnu.system.model.entity.User;
import com.hbnu.system.service.IArtQualificationService;
import com.hbnu.system.service.IArtService;
import com.hbnu.system.service.IArtauthorService;
import com.hbnu.system.service.IUserService;
import com.hbnu.system.utils.CheckRoleUtil;
import com.hbnu.system.utils.IdGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 艺术成果作者服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2023-05-16
 */
@Service
public class Art_authorServiceImpl extends ServiceImpl<Art_authorMapper, Art_author> implements IArtauthorService {

    @Autowired
    private IArtauthorService iArtauthorService;

    @Autowired
    private IArtService iArtService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IArtQualificationService iArtQualificationService;

    @Autowired
    private CheckRoleUtil checkRoleUtil;



    private static final List<String> AUTHOR_TYPE_ORDER = Arrays.asList(
            "第一作者", "共同第一作者", "通讯作者", "第二作者", "第三作者", "其他排名"
    );

    private static final DecimalFormat DECIMAL_FORMAT = new DecimalFormat("0.00");

    /**
     * 添加艺术成果作者
     * @param artAuthor
     * @return
     */
    @Override
    public boolean addArtAuthor(Art_author artAuthor) {

        System.out.println(artAuthor);
        // 不使用前端传过来的id，而是生成一个新的id
        artAuthor.setArtAuthorID(null);
        Art art = iArtService.query().eq("ArtID", artAuthor.getArtID()).one();
        checkRoleUtil.checkPermissionAchievement(art.getStatus());

        //如果是校外作者或者学生，为其生成工号
        if (artAuthor.getPeopleType().equals(AuthorTypeConstants.OUT_SCHOOL_AUTHOR)
                ||artAuthor.getPeopleType().equals(AuthorTypeConstants.STUDENT)) {
            artAuthor.setUserAccount(IdGenerator.generateId());
        }

//        if (artAuthor.getUserAccount().isEmpty()) {
//            throw new BaseException("请输入工号");
//        }

        if (StrUtil.isBlank(artAuthor.getUserAccount())) {
            throw new BaseException("请输入工号");
        }

        Art_author pa1 = iArtauthorService.getOne(Wrappers.lambdaQuery(Art_author.class)
                .eq(Art_author::getArtID, artAuthor.getArtID())
                .eq(Art_author::getUserAccount, artAuthor.getUserAccount()));
        if (Objects.nonNull(pa1)) {
            throw new BaseException("不可重复添加");
        }
        if (StrUtil.isBlank(artAuthor.getAssessment())) {
            throw new BaseException("请输入考核系数");
        }

        double newAssessment;
        try {
            String assessment = artAuthor.getAssessment();
            // 如果考核系数为null或空，默认为0
            if (assessment == null || assessment.trim().isEmpty()) {
                newAssessment = 0.0;
            } else {
                newAssessment = Double.parseDouble(assessment);
            }
        } catch (NumberFormatException e) {
            throw new BaseException("考核系数格式不正确");
        }
        if (newAssessment > 100 || newAssessment < 0) {
            throw new BaseException("输入数据应在0-100范围内");
        }

        String Pscore = "0.00";

//        Art_Qualification artQualification = iArtQualificationService.getById(artAuthor.getArtID());

//        if(art != null){
//            float finalValue = Float.parseFloat(art.getScore());
//            // 计算并保留两位小数
//            double pscore = finalValue * newAssessment / 100.0;
//            Pscore = DECIMAL_FORMAT.format(pscore);
//        }
        // 修改后
        if(art != null){
            String scoreStr = art.getScore();
            // 处理score为null的情况，默认为0
            float finalValue = StrUtil.isBlank(scoreStr) ? 0 : Float.parseFloat(scoreStr.trim());
            // 计算并保留两位小数
            double pscore = finalValue * newAssessment / 100.0;
            Pscore = DECIMAL_FORMAT.format(pscore);
        }

        // 判断加起来总分是否超过100
        List<Art_author> artAuthorList = iArtauthorService.listAuthor(artAuthor.getArtID());
        double sum = 0;
        for (Art_author author : artAuthorList) {
            if(author.getAssessment().equals("")){
                throw new BaseException("请补全所有作者考核系数");
            }
            sum += Double.parseDouble(author.getAssessment());
        }
        if (sum + newAssessment > 100) {
            throw new BaseException("作者考核系数总和大于100!");
        }

        artAuthor.setPscore(Pscore);

        // 如果新增的作者是第一作者的话，要判断是否已经有第一作者
        if ("第一作者".equals(artAuthor.getAuthortype())) {
            for (Art_author author : artAuthorList) {
                if ("第一作者".equals(author.getAuthortype())) {
                    throw new BaseException("该成果已存在第一作者!");
                }
            }
        }

        save(artAuthor);

        // 维护AllAuthor字段
        updateAllAuthor(art, artAuthor);

        return true;
    }

    /**
     * 删除艺术成果作者
     * @param id
     * @return
     */
    @Override
    public boolean deleteArtAuthor(String id) {
        Art_author artAuthor = super.getOne(Wrappers.lambdaQuery(Art_author.class)
                .eq(Art_author::getArtAuthorID, id));
        Art art = iArtService.query().eq("ArtID", artAuthor.getArtID()).one();
        checkRoleUtil.checkPermissionAchievement(art.getStatus());

        boolean result = baseMapper.deleteById(artAuthor) == 1;

        // 维护AllAuthor字段
        if (result) {
            updateAllAuthor(art, artAuthor);
        }

        return result;
    }

    /**
     * 修改艺术成果作者
     * @param artAuthor
     * @return
     */
    @Override
    public boolean updateArtAuthor(Art_author artAuthor) {
        Art art = iArtService.query().eq("ArtID", artAuthor.getArtID()).one();
        checkRoleUtil.checkPermissionAchievement(art.getStatus());
        double newAssessment;
        try {
            String assessment = artAuthor.getAssessment();
            // 如果考核系数为null或空，默认为0
            if (assessment == null || assessment.trim().isEmpty()) {
                newAssessment = 0.0;
            } else {
                newAssessment = Double.parseDouble(assessment);
            }
        } catch (NumberFormatException e) {
            throw new BaseException("考核系数格式不正确");
        }
        if (newAssessment > 100 || newAssessment < 0) {
            throw new BaseException("输入数据应在0-100范围内");
        }

        // 查询该成果的所有作者
        List<Art_author> artAuthorList = query().eq("ArtID", artAuthor.getArtID()).list();

        double sum = 0;
        // 只计算已填写考核系数的作者（排除当前修改的作者）
        for (Art_author author : artAuthorList) {
            if (!author.getArtAuthorID().equals(artAuthor.getArtAuthorID())) {
                if(!StrUtil.isBlank(author.getAssessment())){
                    sum += Double.parseDouble(author.getAssessment());
                }
            }
        }
        // 检查已填写考核系数的总和是否超过100
        if (sum + newAssessment > 100) {
            throw new BaseException("已填写作者考核系数总和大于100");
        }

        String Pscore = "0.00";

//        Art_Qualification artQualification = iArtQualificationService.getById(artAuthor.getArtID());
//        if(art != null){
//            float finalValue = Float.parseFloat(art.getScore());
//            // 计算并保留两位小数
//            double pscore = finalValue * newAssessment / 100.0;
//            Pscore = DECIMAL_FORMAT.format(pscore);
//        }
        // 修改后
        if(art != null){
            String scoreStr = art.getScore();
            // 处理score为null的情况，默认为0
            float finalValue = StrUtil.isBlank(scoreStr) ? 0 : Float.parseFloat(scoreStr.trim());
            // 计算并保留两位小数
            double pscore = finalValue * newAssessment / 100.0;
            Pscore = DECIMAL_FORMAT.format(pscore);
        }

        artAuthor.setPscore(Pscore);

        boolean result = baseMapper.updateById(artAuthor) == 1;

        // 维护AllAuthor字段
        if (result) {
            updateAllAuthor(art, artAuthor);
        }

        return result;
    }

    /**
     * 查询艺术成果的作者列表
     * @param id 成果ID
     * @return 作者列表
     */
    @Override
    public List<Art_author> listAuthor(String id) {
        List<Art_author> list = baseMapper.selectList(Wrappers.lambdaQuery(Art_author.class)
                .eq(Art_author::getArtID, id));

        list.sort(Comparator.comparingInt(p -> AUTHOR_TYPE_ORDER.indexOf(p.getAuthortype())));
        return list;
    }



    /**
     * 维护AllAuthor字段
     * @param art
     * @param artAuthor
     */
    private void updateAllAuthor(Art art, Art_author artAuthor) {
        // 1. 先清空原来的AllAuthor字段
        art.setAllAuthor(null);
        iArtService.updateById(art);

        // 2. 查询该成果的所有作者
        List<Art_author> allAuthorList = iArtauthorService.listAuthor(artAuthor.getArtID());

        // 3. 按照作者类型排序
        allAuthorList.sort(Comparator.comparingInt(p -> AUTHOR_TYPE_ORDER.indexOf(p.getAuthortype())));

        // 4. 获取用户主键ID
        List<String> userAccountList = allAuthorList.stream()
                .map(Art_author::getUserAccount)
                .collect(Collectors.toList());

        List<User> userList = Collections.emptyList();
        if (!userAccountList.isEmpty()) {
            userList = iUserService.list(Wrappers.lambdaQuery(User.class)
                    .in(User::getAccount, userAccountList));
        }

        List<String> uidList = userList.stream()
                .map(User::getUid)
                .collect(Collectors.toList());

        // 5. 拼接字符串
        String allAuthor = String.join(",", uidList);

        // 6. 更新AllAuthor字段
        art.setAllAuthor(allAuthor);
        iArtService.updateById(art);
    }
}
